from django.shortcuts import render, redirect
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from django import forms
from app01.utils.pagination import Pagination
from app01 import models
from app01.utils.bootstrapForm import BootstrapModelForm


class PrettynumModelForm(BootstrapModelForm):
    """靓号 modelForm"""
    # 号码格式校验
    # 使用正则表达式对手机号校验
    mobile = forms.CharField(label="手机号", validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号码格式错误！')])

    class Meta:
        model = models.PrettyNum
        fields = '__all__'

    def clean_mobile(self):
        """使用钩子方式对用户提交的数据校验"""
        # 手机号不能重复，即已有手机号不能再添加
        txt_mobile = self.cleaned_data['mobile']
        if_exist = models.PrettyNum.objects.filter(mobile=txt_mobile).exists()
        if if_exist:
            raise ValidationError("该号码已经存在！")
        return txt_mobile


def prettynum_list(request):
    """靓号列表"""
    # 创建数据
    # one_pretty_num = {
    #     'mobile': '19987032871',
    #     'price': 399,
    #     'level': 2,
    #     'status': 2
    # }
    # for i in range(0, 300):
    #     models.PrettyNum.objects.create(**one_pretty_num)
    # 获取查询字符串，为空则取空字符串
    query_str = request.GET.get('query_str', '')
    queryset = models.PrettyNum.objects.filter(mobile__contains=query_str).order_by('-level')

    page_object = Pagination(request, queryset)
    html_text = page_object.html
    page_query_set = page_object.page_query_set
    context = {
        'prettynums': page_query_set,
        'page_html': html_text,
        'query_str': query_str,
    }
    return render(request, 'prettynum_list.html', context)


def prettynum_add(request):
    """添加靓号"""
    if request.method == "GET":
        form = PrettynumModelForm()
        return render(request, 'prettynum_add.html', {"form": form})
    form = PrettynumModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/prettynum/list/')
    return render(request, 'prettynum_add.html', {'form': form})


class PrettyNumEditModelForm(forms.ModelForm):
    mobile = forms.CharField(label='手机号',
                             validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号码格式错误！')])

    class Meta:
        model = models.PrettyNum
        fields = ['mobile', 'price', 'status']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = field.label

    def clean_mobile(self):
        """定义钩子，编辑后的提交的记录不能同除自己外的手机号重复"""
        txt_mobile = self.cleaned_data['mobile']
        if_exist = models.PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=txt_mobile).exists()
        if if_exist:
            raise ValidationError("改号码已经存在！")
        return txt_mobile


def prettynum_edit(request, nid):
    """编辑靓号"""
    row_object = models.PrettyNum.objects.filter(id=nid).first()
    # 以GET方式访问页面
    if request.method == "GET":
        form = PrettyNumEditModelForm(instance=row_object)
        return render(request, 'prettynum_edit.html', {"form": form})
    # 以POST方式提交数据
    form = PrettyNumEditModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/prettynum/list/')
    return render(request, 'prettynum_edit.html', {'form': form})


def prettynum_delete(request, nid):
    """删除靓号"""
    models.PrettyNum.objects.filter(id=nid).delete()
    return redirect('/prettynum/list/')